package com.samuel.blog.interceptor;

import com.samuel.blog.constant.CommonConstant;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * url 判断
 * @author kaiji
 * @since 2017-12-28
 */
public class UrlInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// /blog-controller/admin/
		String requestURI = request.getRequestURI();
		String str;
		if (requestURI.indexOf(".html") == -1) {
			boolean falg = false;
			if(requestURI.endsWith("/")) {
				str = requestURI.substring(requestURI.indexOf("admin/"), requestURI.length());
				str = str.substring(0, str.length()-1);
				
			} else {
				str = requestURI.substring(requestURI.indexOf("admin"), requestURI.length());
			}
			
			String strs = CommonConstant.URI_LIST;
			String[] uriList = strs.split(",");
			for (String uri : uriList) {
				if (uri.equals(str)) {
					falg = true;
					break;
				}
			}
			if (falg) {
			    // 以 admin结尾的   类似/blog-controller/admin/
				response.sendRedirect(request.getContextPath() + "/admin/home/index.html");
				return false;
			}
			
			return false;
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}

}
